package com.example.springboot.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.example.springboot.listener.TestListener;
import com.example.springboot.servlet.ServletTest;
import com.example.springboot.filter.TestFilter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 注册bean
 */
@Configuration
public class WebConfig {

	/**
	 * 注册fasjoson注入bean
	 *
	 * @return
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {

		//json转化对象
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

		//json配置对象
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		converter.setFastJsonConfig(fastJsonConfig);

		return new HttpMessageConverters(converter);
	}

	/**
	 * 注册自定义servlet
	 *
	 * @return
	 */
	@Bean
	public ServletRegistrationBean servletRegistrationBean() {

		return new ServletRegistrationBean(new ServletTest(), "/servletTest");
	}


	/**
	 * 注册过滤器,有两种方式：
	 * 1) 使用 @Component 注解<br>
	 * 2) 添加到过滤器链中，此方式适用于使用第三方的过滤器。将过滤器写到 WebConfig 类中，如下：
	 */
	@Bean
	public FilterRegistrationBean filterRegistrationBean() {

		FilterRegistrationBean registrationBean = new FilterRegistrationBean();

		TestFilter testFilter = new TestFilter();
		registrationBean.setFilter(testFilter);

		//设置过滤器拦截请求
		List<String> urls = new ArrayList<>();
		urls.add("/*");
		registrationBean.setUrlPatterns(urls);

		return registrationBean;
	}

	/**
	 * 注册监听器
	 */
	@Bean
	public ServletListenerRegistrationBean servletListenerRegistrationBean() {

		ServletListenerRegistrationBean listenerRegistrationBean = new ServletListenerRegistrationBean();
		listenerRegistrationBean.setListener(new TestListener());

		return listenerRegistrationBean;
	}


}